<template>
  <div class="login">
    <div class="login-logo">
      <image src="@/static/wczd/wczd-logo.png"></image>
    </div>
    <div class="login-cont">
      <div class="title">
        <div>欢迎登录</div>
        <div style="font-size: 35upx;font-weight: bold">安全生产数字化智能管控平台</div>
      </div>
      <div class="loginWay">
        <div class="title-item" @click="loginActive='1'" :class="loginActive==='1'?'active-title':''">账号登录</div>
        <div class="title-item" @click="loginActive='2'" :class="loginActive==='2'?'active-title':''">短信登录</div>
      </div>
      <div class="content" v-if="loginActive==='2'">
        <uni-forms :modelValue="formData" label-position="top" ref="form" :rules='rules'>
          <uni-forms-item label="手机号：" label-width='160' name="phone">
            <uni-easyinput type="text" v-model="formData.phone" placeholder="请填写手机号" />
          </uni-forms-item>
          <uni-forms-item label="验证码：" name="captchaCode">
            <uni-easyinput type="number" style="width: 63%" v-model="formData.captchaCode" placeholder="请填写验证码" />
            <div class="login-code">
              <div v-if="!codeFlag" class="code-btn" @click="getPhoneVerifyCode()">获取验证码</div>
              <div v-else class="code-btn">{{second+'s'}}</div>
            </div>
          </uni-forms-item>
          <button :disabled="loading" :loading="loading" class="unibtn" type="primary" @click="submit">
            <span v-if="!loading">登 录</span>
            <span v-else>登 录 中...</span>
          </button>
          <!-- <div class="footer">点击登录，即表示您同意<a>《用户协议》</a></div> -->
        </uni-forms>
      </div>
      <div class="content" v-if="loginActive==='1'">
        <uni-forms :modelValue="countFormData" label-position="top" ref="countForm" :rules='countRules'>
          <uni-forms-item label="账号：" label-width='160' name="username">
            <uni-easyinput type="text" v-model="countFormData.username" placeholder="请填写账号" />
          </uni-forms-item>
          <uni-forms-item label="密码：" label-width='160' name="password">
            <uni-easyinput type="password" v-model="countFormData.password" placeholder="请填写密码" />
          </uni-forms-item>
          <uni-forms-item label="验证码：" name="code">
            <uni-easyinput type="number" style="width: 63%" v-model="countFormData.code" placeholder="请填写验证码" />
            <div class="login-code">
              <image :src="codeUrl" class="login-code-img" @click="getCode"></image>
            </div>
          </uni-forms-item>
          <button :disabled="countLoading" :loading="countLoading" class="unibtn" type="primary" @click="countSubmit">
            <span v-if="!countLoading">登 录</span>
            <span v-else>登 录 中...</span>
          </button>
          <!-- <div class="footer">点击登录，即表示您同意<a>《用户协议》</a></div> -->
        </uni-forms>
      </div>
    </div>
  </div>
</template>

<script>
import UniForms from '@/components/uni-forms/uni-forms.vue'
import UniFormsItem from '@/components/uni-forms-item/uni-forms-item.vue'
import UniEasyinput from '@/components/uni-easyinput/uni-easyinput.vue'
import { getCodeImg, login, getRSAKey, getPhoneVerifyCode } from '@/api/login'
import { removeToken, getToken } from '@/utils/auth'
import JSEncrypt from '@/utils/jsencrypt'
let timer = null

export default {
  name: 'login',
  components: { UniForms, UniFormsItem, UniEasyinput },
  data () {
    return {
      loginActive: '1',
      codeUrl: '',
      codeFlag: false,
      second: 60,
      formData: {
        phone: '',
        captchaCode: '',
      },
      countFormData: {
        username: '',
        password: '',
        code: '',
        uuid: ''
      },
      publicKey: '',
      loading: false,
      countLoading: false,
      rules: {
        phone: {
          rules: [{ required: true, errorMessage: '手机号不能为空', }]
        },
        captchaCode: {
          rules: [{ required: true, errorMessage: '验证码不能为空', }]
        }
      },
      countRules: {
        username: {
          rules: [{ required: true, errorMessage: '账号不能为空', }]
        },
        password: {
          rules: [{ required: true, errorMessage: '密码不能为空', }]
        },
        code: {
          rules: [{ required: true, errorMessage: '验证码不能为空', }]
        },
      }
    }
  },
  onLoad () {
    removeToken()
    if (getToken()) {
      uni.reLaunch({
        url: '/pages/home/home'
      });
    } else {
      this.getCode()
    }
  },
  mounted () {
    getRSAKey().then(res => {
      this.publicKey = res.msg
    })
  },
  watch: {
    loginActive: function (val) {
      this.reset()
      this.countReset()
      this.getCode()
    }
  },
  methods: {
    getCode () {
      getCodeImg().then(res => {
        this.codeUrl = 'data:image/gif;base64,' + res.img
        this.countFormData.uuid = res.uuid
      })
    },
    getPhoneVerifyCode () {
      if (!this.formData.phone) {
        uni.showToast({
          icon: 'none',
          title: '请输入手机号',
          duration: 2000,
        });
        return;
      }
      getPhoneVerifyCode({ phone: this.formData.phone }).then(res => {
        this.codeFlag = true
        this.second = 60
        timer = setInterval(() => {
          this.second--
          if (this.second === 0) {
            this.codeFlag = false
            clearInterval(timer)
          }
        }, 1000)
      })
    },
    reset () {
      this.formData = {
        phone: '',
        captchaCode: '',
      }
    },
    countReset () {
      this.countFormData = {
        username: '',
        password: '',
        code: '',
        uuid: ''
      }
    },
    // 提交
    countSubmit () {
      this.countLoading = true
      var crypt = new JSEncrypt()
      crypt.setPublicKey(this.publicKey)
      var username = crypt.encrypt(this.countFormData.username)
      var password = this.countFormData.password
      if (this.countFormData.password.length < 50) {
        password = crypt.encrypt(this.countFormData.password)
      }
      const obj = { ...this.countFormData }
      obj.username = username
      obj.password = password
      obj.code = crypt.encrypt(this.countFormData.code)
      this.$refs.countForm.validate().then(res => {
        this.$store
          .dispatch('Login', obj)
          .then(() => {
            console.log('登录成功');
            uni.showToast({
              icon: 'none',
              title: '登录成功',
              duration: 2000,
            });
            setTimeout(() => {
              uni.reLaunch({
                url: '/pages/home/home'
              });
            }, 1000);
          })
          .catch(error => {
            uni.showToast({
              icon: 'none',
              title: error,
              duration: 2000,
            });
            this.countLoading = false
            this.getCode()
            this.countFormData.code = ''
          })
      }).catch(err => {
        this.countLoading = false
        uni.showToast({
          icon: 'none',
          title: err[0].errorMessage,
          duration: 2000,
        });
      })
    },
    // 提交
    submit () {
      this.loading = true
      var crypt = new JSEncrypt()
      crypt.setPublicKey(this.publicKey)
      var phone = crypt.encrypt(this.formData.phone)
      var captchaCode = crypt.encrypt(this.formData.captchaCode)
      var obj = { phone, captchaCode }
      this.$refs.form.validate().then(res => {
        this.$store
          .dispatch('loginByPhone', obj)
          .then(() => {
            uni.showToast({
              icon: 'none',
              title: '登录成功',
              duration: 2000,
            });
            setTimeout(() => {
              uni.reLaunch({
                url: '/pages/home/home'
              });
            }, 1000);
          })
          .catch(error => {
            this.loading = false
          })
      }).catch(err => {
        this.loading = false
        uni.showToast({
          icon: 'none',
          title: err[0].errorMessage,
          duration: 2000,
        });
      })
    }
  },
}
</script>

<style scoped lang="scss">
.login {
  height: 100%;
  background: url("@/static/wczd/login-bk.png") no-repeat;
  background-size: 100% 40%;
  background-color: #f1f4f6;
  display: flex;
  flex-direction: column;
  align-items: center;
  .login-logo {
    height: 26%;
    display: flex;
    align-items: center;
    > image {
      width: 200upx;
      height: 200upx;
    }
  }
  .login-cont {
    width: 80%;
    background-color: #ffffff;
    border-radius: 10px;
    padding: 3vh 40upx 3vh 40upx;
    .unibtn {
      margin-top: 40upx;
    }
    .content {
      .footer {
        color: #75787b;
        padding: 20upx;
        text-align: center;
        font-size: 14upx;
      }
    }
  }
}
.login-code {
  .login-code-img {
    height: 60upx;
    width: 160upx;
    vertical-align: middle;
    > image {
      width: 160upx;
      height: 60upx;
    }
  }
}
.loginWay {
  display: flex;
  color: #b3b3b3;
  align-items: flex-end;
  .title-item {
    width: 48%;
    text-align: center;
    padding: 4px 0;
    border-bottom: 4px solid rgb(255, 255, 255);
    font-size: 30upx;
    font-weight: 500;
  }
  .active-title {
    color: #009fdf;
    border-bottom: 4px solid #009fdf;
    font-size: 30upx;
    font-weight: 500;
  }
}
/deep/.uni-icons.content-clear-icon {
  display: none;
}
</style>
